//
//  L9Logger.m
//  Lesson109
//
//  Created by 徐盟 on 2023/3/6.
//

#import "XMLogger.h"


@implementation XMLogger

-(instancetype) init
{
    if (self == [super init]) {
        self.isOpen = YES;
    }
    return  self;
}

- (instancetype) initWithScopeName:(NSString *) scopeName
{
    static NSMutableDictionary* instances = nil;
    if (instances == nil) {
        instances = [NSMutableDictionary dictionary];
    }

    if ([instances objectForKey: scopeName] == nil) {
        if(self = [self init]){
             self.scopeName =  scopeName;
            [instances setObject:self forKey:scopeName];
        }
    }
    
    return [instances objectForKey: scopeName];
}

+(instancetype) loggerWithScopeName:(NSString *) scopeName
{
    return  [[XMLogger alloc] initWithScopeName:scopeName];
}

- (BOOL)isOpen
{
    if (_isOpen != NO) {
        _isOpen = YES;
    }
    return _isOpen;
}

-(void)open
{
    self.isOpen = YES;
}
-(void)close
{
    self.isOpen = NO;
}

-(void) log:(NSString *)format,...
{
    if (!self.isOpen) {
        return;
    }
    NSString* newFormat = [@"XMLogger " stringByAppendingFormat:@"【%@】 %@",self.scopeName, format];
    
    va_list ap;
    va_start(ap, format);
    NSLogv(newFormat, ap);
    va_end(ap);
}
-(void) logv:(NSString *)format args:(va_list) args;
{
    if (!self.isOpen) {
        return;
    }
    NSString* newFormat = [@"XMLogger " stringByAppendingFormat:@"【%@】 %@",self.scopeName, format];
    NSLogv(newFormat, args);
}

+(NSString *) formatArray:(NSArray*) arr
{
    NSMutableString *str = [NSMutableString stringWithFormat:@"%lu (\n", (unsigned long)arr.count];
 
    for (id obj in self) {
        [str appendFormat:@"\t%@, \n", obj];
    }
 
    [str appendString:@")"];
 
    return str;
}

+(NSString *) formatDictionary:(NSDictionary*) dict
{
    NSArray *allKeys = [dict allKeys];
    NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"{\t\n "];
    for (NSString *key in allKeys) {
        id value= dict[key];
        [str appendFormat:@"\t \"%@\" = %@,\n",key, value];
    }
   [str appendString:@"}"];

    return str;
}

+(void) log:(NSString *)format,...
{
    NSString* newFormat = [@"XMLogger " stringByAppendingFormat:@"%@", format];
    
    va_list ap;
    va_start(ap, format);
    NSLogv(newFormat, ap);
    va_end(ap);
}

-(void (^)(NSString *format,...)) log
{
    return ^void(NSString *format,...){
        if (!self.isOpen) {
            return;
        }
        NSString* newFormat = [@"XMLogger " stringByAppendingFormat:@"【%@】 %@",self.scopeName, format];
        
        va_list ap;
        va_start(ap, format);
        NSLogv(newFormat, ap);
        va_end(ap);
    };
}

@end
